#define _CRT_SECURE_NO_WARNINGS 1
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
using pii = pair<int, int>;
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
class Solution {
public:
    void bfs(vector<vector<char> >& grid, int srci, int srcj
        , vector<vector<bool>>& vis)
    {
        queue<pii> q;
        q.push({ srci,srcj });
        vis[srci][srcj] = true;
        while (!q.empty())
        {
            int a = q.front().first;
            int b = q.front().second;
            q.pop();
            for (int i = 0;i < 4;++i)
            {
                int x = a + dx[i], y = b + dy[i];
                if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() &&
                    grid[x][y] == '1' && vis[x][y] == false)
                {
                    q.push({ x,y });
                    vis[x][y] = true;
                }
            }
        }
    }
    int solve(vector<vector<char> >& grid)
    {
        vector<vector<bool>> vis(grid.size(), vector<bool>(grid[0].size(), false));
        int count = 0;
        for (int i = 0;i < grid.size();++i)
        {
            for (int j = 0;j < grid[i].size();++j)
            {
                cerr << grid[i][j] << endl;
                if (grid[i][j] == '1' && vis[i][j] == false)
                {
                    //cerr<<"i="<<i<<",j="<<j<<endl;
                    ++count;
                    bfs(grid, i, j, vis);
                    // for(auto a:vis)
                    // {
                    //     for(auto b:a) cerr<<b<<" ";
                    //     cerr<<endl;
                    // }
                }
            }
        }
        return count;
    }
};